package com.huang.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i < 10; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.put("k1","v1");
            },String.valueOf(i).toString()).start();
        }


        for (int i = 0; i < 10; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.get("kkk1");
            },String.valueOf(i).toString()).start();
        }




    }
}
/*
*  自定义缓存
*
* */
class MyCache{
     private volatile Map<String,Object> map=new HashMap<>();
     ReadWriteLock rwLock=new ReentrantReadWriteLock();  //读写锁   更加细致控制读写
     //存  写  控制同时只有一个线程在写
    public void put(String key,Object value){
        rwLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"-----开始写");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"-----写成功");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rwLock.writeLock().unlock();
        }

    }

    public void get(String key){
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"-----开始读");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"-----读成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }

    }
}
